<?php
namespace Admin\Model;
use Think\Model;

class LockModel extends Model{

	public function getQrcodePath($lock_id){
		//获取锁信息
		$lock_info  = $this->getLockInfo($lock_id);
    
        //设置二维码存放路径
        $img_path = 'Uploads/qrcode/'.$lock_info['box_number'];
        //设置图片名称 智能柜编号_控制板编号_锁号
        $img_name = $lock_info['box_number'].'_'.$lock_info['control_board_number'].'_'.$lock_info['lock_number'].'.jpg';
        
        $qrcode_path = $img_path.'/'.$img_name;
        if(!is_file($qrcode_path)){
        	//创建空文件夹
	        if (!file_exists($img_path)){
	            @ mkdir($img_path,0777,true);
	        }
	        $number = $lock_info['control_board_number'].$lock_info['lock_number'];
	        file_put_contents($qrcode_path, $this->getWxaqrcode($number));

	        //二维码裁剪
	        $this->cropWxaqrcode($qrcode_path);
        }
        //图片合成
        //$this->synthesisNewWxaqrcode($qrcode_path);


        return $qrcode_path;
	}

	//获取锁信息
	public function getLockInfo($lock_id){
		return M('Lock')->where('id = '.$lock_id)->find();
	}

	//裁剪小程序二维码
	private function cropWxaqrcode($qrcode_path){
        $image = new \Think\Image();
	    $image->open($qrcode_path);
	    //将图片裁剪为400x400并保存为corp.jpg
	    $image->crop(412, 412,5,5)->save($qrcode_path); 
	}

	//合成最终的二维码图片
	private function synthesisNewWxaqrcode($qCodePath){ 

        $bigImg     = imagecreatefromstring(file_get_contents("Uploads/qrcode_bg/qrcode_bg.jpg")); 

        $bigImgPath = "Uploads/qrcode_bg/qrcode_bg.jpg";  
		  
		  
		$bigImg = imagecreatefromstring(file_get_contents($bigImgPath));  
		$qCodeImg = imagecreatefromstring(file_get_contents($qCodePath));  
		  
		list($qCodeWidth, $qCodeHight, $qCodeType) = getimagesize($qCodePath);  
		  
		imagecopymerge($bigImg, $qCodeImg, 175, 260, 0, 0, $qCodeWidth, $qCodeHight, 100);  
		   
		list($bigWidth, $bigHight, $bigType) = getimagesize($bigImgPath);  
		  
		imagejpeg($bigImg,'Uploads/123.png');  
	}

	private function getWxaqrcode($number){
		$access_token = getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=$access_token";
	   
      
        $data['path']  = '/pages/index/index?query='.$number;
        $data['width'] = "420";

        return httpRequest($url,'POST',json_encode($data));
	}


}

